<?php
class Pdb { 
    private $dbhost;
    private $dbuser;
    private $dbpwd;
    private $dbname;
    private $dbport;
    private $dbsocket;
        
    public $queries;
    public function __construct($dbhost, $dbuser,$dbpwd, $dbname, $port=3306, $socket=NULL){
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpwd  = $dbpwd;
        $this->dbname = $dbname;
        $this->dbport = $port;
        $this->dbsocket = $socket;
        
    }
    
    /**
     * 只有在需要的情况下，才去建立数据库连接
     * @param string $name
     */
    public function __get($name){
        if ($name === 'dbh'){
            $this->dbh = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpwd, $this->dbname,
                $this->dbport, $this->dbsocket);
            mysqli_query($this->dbh, 'SET names utf8');
            return $this->dbh;
        }
    }

    public function fetch($sql){
        defined(DB_PROFILE) && $this->queries[] = $sql;
        $dbr = mysqli_query($this->dbh, $sql);
        $row = mysqli_fetch_assoc($dbr);
        mysqli_free_result($dbr);
        return $row;
    }
    
    public function fetch_all($sql){
        defined(DB_PROFILE) && $this->queries[] = $sql;
        $dbr = mysqli_query($this->dbh, $sql);
        if (mysqli_errno($this->dbh)){
            echo mysqli_error($this->dbh) .'---------------'.$sql;
            
        }
        $rows = array();
        while($row = mysqli_fetch_assoc($dbr)){
            $rows[] = $row;
        }
        mysqli_free_result($dbr);
        return $rows;
    }
    
    public function fetch_col($sql){
        defined(DB_PROFILE) && $this->queries[] = $sql;
        $row = mysqli_fetch_array(mysqli_query($this->dbh, $sql));
        return $row[0];
    }
    
    public function insert($sql){
        mysqli_query($this->dbh, $sql);
        return mysqli_insert_id($this->dbh);
    }
    
    public function delete($sql){
        mysqli_query($this->dbh, $sql);
        return mysqli_affected_rows($this->dbh);
    }
    
    /**
     * replace or update  a row or rows
     */
    public function replace($sql){
        mysqli_query($this->dbh, $sql);
        return mysqli_affected_rows($this->dbh);
    }
    // profile the sql has executed show the time and index used
    public function profile(){
        foreach ($this->queries as $sql) {
        	$ret[$sql] = mysqli_fetch_assoc(mysqli_query($this->dbh, "EXPLAIN ".$sql));
        }
        return $ret;
    }
    
}